const response = require("../../utils/response");
const { handleDatabaseError } = require("../../utils/dberrordeal");
const RoleService = require('../../services/system/roleService');

class RoleController {
    static async addRole(ctx) {
        const roleData = ctx.request.body;
        await RoleService.createRole(roleData)
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, "角色名称已存在"));
    }

    static async updateRole(ctx) {
        const { id, ...roleData } = ctx.request.body;
        await RoleService.updateRole(id, roleData)
            .then(() => response.success(ctx, {}))
            .catch(() => response.error(ctx, {}));
    }

    static async getRoleById(ctx) {
        const { id } = ctx.request.body;
        await RoleService.getRoleById(id)
            .then(res => response.success(ctx, { data: res }))
            .catch(() => response.error(ctx, {}));
    }

    static async getRoleList(ctx) {
        await RoleService.getRoleList()
            .then(res => response.success(ctx, { data: res }))
            .catch(() => response.error(ctx, {}));
    }

    static async deleteRole(ctx) {
        const { id } = ctx.request.body;
        await RoleService.deleteRole(id)
            .then(() => response.success(ctx, {}))
            .catch(() => response.error(ctx, {}));
    }
}

module.exports = RoleController;
